package com.lin.sqltool.controller;

import com.lin.sqltool.config.DataBaseConfig;

import com.lin.sqltool.factory.ConnectionServiceFactory;
import com.lin.sqltool.listener.SimpleConnectionListener;
import com.lin.sqltool.model.ConnectionInfoModel;
import com.lin.sqltool.service.ConnectionService;
import com.lin.sqltool.utils.ConnectionUtil;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.stage.Stage;

import java.util.Optional;

import static com.lin.sqltool.utils.CommonUtil.showAlert;


public class ConnectionDialogController {

    @FXML
    private ComboBox<String> nameComboBox;

    @FXML
    private TextField hostField;

    @FXML
    private TextField portField;

    @FXML
    private TextField userField;

    @FXML
    private PasswordField passwordField;

    @FXML
    private ComboBox<String> databaseTypeComboBox;

    private SimpleConnectionListener listener;

    public void setListener(SimpleConnectionListener listener) {
        this.listener = listener;
    }




    public void initialize() {
        databaseTypeComboBox.getItems().addAll(DataBaseConfig.DATA_BASE_TYPE_LIST);
        databaseTypeComboBox.setValue("mysql"); //设置默认值
        databaseTypeComboBox.setDisable(true);
        nameComboBox.getItems().addAll(ConnectionUtil.getConnectionsNames());
        nameComboBox.getSelectionModel().selectFirst();

        //将第一个设置进去
        ConnectionInfoModel first = ConnectionUtil.getConnections().get(0);
        hostField.setText(first.getHost());
        portField.setText(first.getPort());
        userField.setText(first.getUsername());
        passwordField.setText(first.getPassword());
        databaseTypeComboBox.setValue(first.getDatabaseType());


        nameComboBox.valueProperty().addListener(new ChangeListener<String>() {
            @Override
            public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
                if (newValue != null) {
                    ConnectionInfoModel connectionInfo = ConnectionUtil.getConnectionByName(newValue);
                    if (connectionInfo != null) {
                        hostField.setText(connectionInfo.getHost());
                        portField.setText(connectionInfo.getPort());
                        userField.setText(connectionInfo.getUsername());
                        passwordField.setText(connectionInfo.getPassword());
                        databaseTypeComboBox.setValue(connectionInfo.getDatabaseType());
                    }
                }
            }
        });
    }


    @FXML
    private void testConnection() {
        String name = nameComboBox.getValue();
        String host = hostField.getText();
        String user = userField.getText();
        String password = passwordField.getText();
        String port = portField.getText();
        String databaseType = databaseTypeComboBox.getValue();

        ConnectionInfoModel connectionInfoModel = new ConnectionInfoModel(name, host, port, user, password, databaseType);
        ConnectionService connectionService = ConnectionServiceFactory.getService(databaseType);
        boolean isConnected = connectionService.testConnection(connectionInfoModel);
        if (isConnected) {
            showAlert(Alert.AlertType.INFORMATION, "连接成功", "数据库连接测试成功！");
        } else {
            showAlert(Alert.AlertType.ERROR, "连接失败", "数据库连接测试失败，请检查配置！");
        }
    }

    @FXML
    private void delConnection() {
        String name = nameComboBox.getValue();
        Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
        alert.setTitle("确认删除");
        alert.setHeaderText("是否确认删除？");
        alert.setContentText("这将永久删除所选内容。");
        Optional<ButtonType> result = alert.showAndWait();
        if (result.isPresent() && result.get() == ButtonType.OK) {
            ConnectionUtil.deleteConnection(name);

            nameComboBox.getItems().remove(name);
            nameComboBox.getSelectionModel().selectFirst();

            //将第一个设置进去
            ConnectionInfoModel first = ConnectionUtil.getConnections().get(0);
            hostField.setText(first.getHost());
            portField.setText(first.getPort());
            userField.setText(first.getUsername());
            passwordField.setText(first.getPassword());
            databaseTypeComboBox.setValue(first.getDatabaseType());

        }
    }

    @FXML
    private void renameConnection() {
        String currentName = nameComboBox.getValue();
        if (currentName == null) {
            showAlert(Alert.AlertType.WARNING, "警告", "请先选择要重命名的连接");
            return;
        }

        TextInputDialog dialog = new TextInputDialog(currentName);
        dialog.setTitle("重命名连接");
        dialog.setHeaderText("请输入新的连接名称");
        dialog.setContentText("新名称:");

        dialog.showAndWait().ifPresent(newName -> {
            if (!newName.isEmpty()) {
                boolean success = ConnectionUtil.renameConnection(currentName, newName);

                if (success) {
                    nameComboBox.getItems().remove(currentName);
                    nameComboBox.getItems().add(newName);
                    nameComboBox.setValue(newName);

                    showAlert(Alert.AlertType.INFORMATION, "成功", "连接名称已更新");
                } else {
                    showAlert(Alert.AlertType.ERROR, "失败", "重命名失败，请检查是否有重复名称");
                }
            }
        });
    }

    @FXML
    private void addConnection() {
        TextInputDialog dialog = new TextInputDialog();
        dialog.setTitle("新建连接");
        dialog.setHeaderText("请输入新的连接名称");
        dialog.setContentText("连接名称:");

        dialog.showAndWait().ifPresent(newName -> {
            if (!newName.isEmpty()) {
                if (nameComboBox.getItems().contains(newName)) {
                    showAlert(Alert.AlertType.ERROR, "错误", "该连接名称已存在，请选择其他名称。");
                } else {
                    nameComboBox.getItems().add(newName);
                    nameComboBox.setValue(newName);

                    hostField.setText("localhost");
                    portField.setText("3306");
                    userField.setText("");
                    passwordField.setText("");
                    databaseTypeComboBox.setValue("mysql");

                    ConnectionInfoModel newConnection = new ConnectionInfoModel(newName, "localhost", "3306", "", "", "mysql");
                    ConnectionUtil.addConnection(newConnection);
                }
            }
        });
    }

    @FXML
    private void handleOk() {
        String name = nameComboBox.getValue();
        String host = hostField.getText();
        String user = userField.getText();
        String password = passwordField.getText();
        String port = portField.getText();
        String databaseType = databaseTypeComboBox.getValue();
        if (host.isEmpty() || user.isEmpty()) {
            showAlert(Alert.AlertType.ERROR,"错误", "主机和用户名为必填");
            return;
        }

        ConnectionInfoModel connectionInfo = new ConnectionInfoModel(name, host, port, user, password, databaseType);
        if (listener != null) {
            ConnectionUtil.saveConnection(connectionInfo);
            listener.onOk(connectionInfo);
        }

        // 关闭对话框
        ((Stage) nameComboBox.getScene().getWindow()).close();
    }


}
